#include "draw_sdl.h"

void draw_init()
{
	SDL_Init( 0 );
	IMG_Init( IMG_INIT_JPG|IMG_INIT_PNG );
	if (TTF_Init() == -1)
		printf("TTF_Init: %s\n", TTF_GetError());
}

void draw_quit()
{
	TTF_Quit();
	IMG_Quit();
	SDL_Quit();
}

DImage *draw_load_image( const char *fname )
{
	SDL_Surface *srf=NULL;
	unsigned int i=strlen(fname);
	const char f_png[] = ".png",f_jpg[] = ".jpg";
	//printf("fname %s\n",fname);
	if (i < 4) return NULL;
	//printf("%s",fname+i-4);
	if ((strncmp(fname+i-4,f_png,4) == 0) || (strncmp(fname+i-4,f_jpg,4) == 0))
	{
		srf = IMG_Load( fname );
		if ( !srf )
		{
			printf("IMG_Load: %s\n", IMG_GetError());
		}
		//printf("Image loaded\n");
	}
	return srf;
}

void draw_save_image( DImage *img, const char *fname)
{
	SDL_SaveBMP( img, fname);
	system("convert save.bmp save.png");
}

DFont* draw_load_font( const char *fname, int size)
{
	DFont *fnt;
	fnt = TTF_OpenFont( fname, size);
	if (!fnt) 
	{
		printf("TTF_OpenFont: %s\n", TTF_GetError());
	}
	return fnt;
}

void draw_font( DImage *img_srf , DFont *fnt, int x, int y, int color, const char *txt )
{
	SDL_Color sdl_color;
	sdl_color.r = (color&0x00ff0000) >> 16;
	sdl_color.g = (color&0x0000ff00) >> 8;
	sdl_color.b = (color&0x000000ff) ;
	DImage *font_text = TTF_RenderText_Solid( fnt , txt, sdl_color);
	SDL_Rect offset;
	offset.x = x;
	offset.y = y;
	SDL_BlitSurface( font_text, NULL, img_srf, &offset );
	SDL_FreeSurface( font_text );
}

void draw_free_surface( DImage *srf )
{
	SDL_FreeSurface( srf );
}

